<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta name="referrer" content="same-origin">
<meta name="referrer" content="no-referrer" />








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="RocketMQ之旅," />










<meta name="description" content="NamesrvController&amp;emsp;&amp;emsp;namesrv是一个注册中心，每个broker都会向namesrv注册。producer或者consumer根据topic到namesrv获取broker的信息。根据官网Qucik Start来启动namesrv：1234567&amp;gt; unzip rocketmq-all-4.3.0-source-release.zip&amp;gt; cd r">
<meta name="keywords" content="RocketMQ之旅">
<meta property="og:type" content="article">
<meta property="og:title" content="RocketMQ之旅（二）namesrv">
<meta property="og:url" content="http://yoursite.com/2018/08/18/RocketMQ之旅（二）namesrv/index.html">
<meta property="og:site_name" content="矩阵编程">
<meta property="og:description" content="NamesrvController&amp;emsp;&amp;emsp;namesrv是一个注册中心，每个broker都会向namesrv注册。producer或者consumer根据topic到namesrv获取broker的信息。根据官网Qucik Start来启动namesrv：1234567&amp;gt; unzip rocketmq-all-4.3.0-source-release.zip&amp;gt; cd r">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-10-24T16:22:02.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="RocketMQ之旅（二）namesrv">
<meta name="twitter:description" content="NamesrvController&amp;emsp;&amp;emsp;namesrv是一个注册中心，每个broker都会向namesrv注册。producer或者consumer根据topic到namesrv获取broker的信息。根据官网Qucik Start来启动namesrv：1234567&amp;gt; unzip rocketmq-all-4.3.0-source-release.zip&amp;gt; cd r">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/08/18/RocketMQ之旅（二）namesrv/"/>





  <title>RocketMQ之旅（二）namesrv | 矩阵编程</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7d29e6fba8e07d1a8af2414a20e5f2a6";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">矩阵编程</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-主页">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-主页"></i> <br />
            
            主页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-分类"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-所有文章">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-文章"></i> <br />
            
            所有文章
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/08/18/RocketMQ之旅（二）namesrv/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="matrix">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="矩阵编程">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">RocketMQ之旅（二）namesrv</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-18T09:21:28+08:00">
                2018-08-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/RocketMQ之旅/" itemprop="url" rel="index">
                    <span itemprop="name">RocketMQ之旅</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/08/18/RocketMQ之旅（二）namesrv/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2018/08/18/RocketMQ之旅（二）namesrv/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="NamesrvController"><a href="#NamesrvController" class="headerlink" title="NamesrvController"></a>NamesrvController</h3><p>&emsp;&emsp;namesrv是一个注册中心，每个broker都会向namesrv注册。producer或者consumer根据topic到namesrv获取broker的信息。根据官网Qucik Start来启动namesrv：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; unzip rocketmq-all-4.3.0-source-release.zip</span><br><span class="line">&gt; cd rocketmq-all-4.3.0/</span><br><span class="line">&gt; mvn -Prelease-all -DskipTests clean install -U</span><br><span class="line">&gt; cd distribution/target/apache-rocketmq</span><br><span class="line">&gt; nohup sh bin/mqnamesrv &amp;</span><br><span class="line">&gt; tail -f ~/logs/rocketmqlogs/namesrv.log</span><br><span class="line">The Name Server boot success...</span><br></pre></td></tr></table></figure></p>
<p>查看mqnamesrv脚本，指定启动org.apache.rocketmq.namesrv.NamesrvStartup。进入NamesrvStartup查看代码，是一个main函数，主要分两步：<strong>创建NamesrvController</strong>，<strong>启动NamesrvController</strong>，所以我们重点还是看一下NamesrvController这个类。<br><a id="more"></a><br>&emsp;&emsp;顾名思义NamesrvController是一个控制类，NamesrvStartup解析完参数后，交由NamesrvController处理。NamesrvController主要做了以下几件事：</p>
<ol>
<li>启动NettyRemotingServer，并注册网络处理器NettyRequestProcessor，处理不同的请求</li>
<li>启动定时任务线程，扫描并移除不活跃的broker</li>
<li>启动FileWatchService监测tls文件变动</li>
</ol>
<h3 id="NettyRequestProcessor"><a href="#NettyRequestProcessor" class="headerlink" title="NettyRequestProcessor"></a>NettyRequestProcessor</h3><p>NettyRemotingServer在remoting模块里面，启动一个Netty的服务端，这个后续看remoting模块再讨论。DefaultRequestProcessor主要处理NettyRemotingServer的网络请求，可以看一下DefaultRequestProcessor是如何注册进RemotingServer的：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//RemotingServer.class</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerDefaultProcessor</span><span class="params">(NettyRequestProcessor processor, ExecutorService executor)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.defaultRequestProcessor = <span class="keyword">new</span> Pair&lt;NettyRequestProcessor, ExecutorService&gt;(processor, executor);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>包含一个线程池，Pair是一个简单的key-value结构类：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pair</span>&lt;<span class="title">T1</span>, <span class="title">T2</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T1 object1;</span><br><span class="line">    <span class="keyword">private</span> T2 object2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>NettyRemotingServer内部有一个NettyServerHandler来处理消息：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">processMessageReceived</span><span class="params">(ChannelHandlerContext ctx, RemotingCommand msg)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">       <span class="keyword">final</span> RemotingCommand cmd = msg;</span><br><span class="line">       <span class="keyword">if</span> (cmd != <span class="keyword">null</span>) &#123;</span><br><span class="line">           <span class="keyword">switch</span> (cmd.getType()) &#123;</span><br><span class="line">               <span class="keyword">case</span> REQUEST_COMMAND:</span><br><span class="line">                   processRequestCommand(ctx, cmd);</span><br><span class="line">                   <span class="keyword">break</span>;</span><br><span class="line">               <span class="keyword">case</span> RESPONSE_COMMAND:</span><br><span class="line">                   processResponseCommand(ctx, cmd);</span><br><span class="line">                   <span class="keyword">break</span>;</span><br><span class="line">               <span class="keyword">default</span>:</span><br><span class="line">                   <span class="keyword">break</span>;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure></p>
<p>继续看processRequestCommand，这个方法在NettyRemotingServer的父类NettyRemotingAbstract中：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">processRequestCommand</span><span class="params">(<span class="keyword">final</span> ChannelHandlerContext ctx, <span class="keyword">final</span> RemotingCommand cmd)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> Pair&lt;NettyRequestProcessor, ExecutorService&gt; matched = <span class="keyword">this</span>.processorTable.get(cmd.getCode());</span><br><span class="line">    <span class="keyword">final</span> Pair&lt;NettyRequestProcessor, ExecutorService&gt; pair = <span class="keyword">null</span> == matched ? <span class="keyword">this</span>.defaultRequestProcessor : matched;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> opaque = cmd.getOpaque();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (pair != <span class="keyword">null</span>) &#123;</span><br><span class="line">        Runnable run = <span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    RPCHook rpcHook = NettyRemotingAbstract.<span class="keyword">this</span>.getRPCHook();</span><br><span class="line">                    <span class="keyword">if</span> (rpcHook != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        rpcHook.doBeforeRequest(RemotingHelper.parseChannelRemoteAddr(ctx.channel()), cmd);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">final</span> RemotingCommand response = pair.getObject1().processRequest(ctx, cmd);</span><br><span class="line">                    <span class="keyword">if</span> (rpcHook != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        rpcHook.doAfterResponse(RemotingHelper.parseChannelRemoteAddr(ctx.channel()), cmd, response);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">if</span> (!cmd.isOnewayRPC()) &#123;</span><br><span class="line">                        <span class="keyword">if</span> (response != <span class="keyword">null</span>) &#123;</span><br><span class="line">                            response.setOpaque(opaque);</span><br><span class="line">                            response.markResponseType();</span><br><span class="line">                            <span class="keyword">try</span> &#123;</span><br><span class="line">                                ctx.writeAndFlush(response);</span><br><span class="line">                            &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">                                log.error(<span class="string">"process request over, but response failed"</span>, e);</span><br><span class="line">                                log.error(cmd.toString());</span><br><span class="line">                                log.error(response.toString());</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line"></span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">                    log.error(<span class="string">"process request exception"</span>, e);</span><br><span class="line">                    log.error(cmd.toString());</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">if</span> (!cmd.isOnewayRPC()) &#123;</span><br><span class="line">                        <span class="keyword">final</span> RemotingCommand response = RemotingCommand.createResponseCommand(RemotingSysResponseCode.SYSTEM_ERROR,</span><br><span class="line">                            RemotingHelper.exceptionSimpleDesc(e));</span><br><span class="line">                        response.setOpaque(opaque);</span><br><span class="line">                        ctx.writeAndFlush(response);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (pair.getObject1().rejectRequest()) &#123;</span><br><span class="line">            <span class="keyword">final</span> RemotingCommand response = RemotingCommand.createResponseCommand(RemotingSysResponseCode.SYSTEM_BUSY,</span><br><span class="line">                <span class="string">"[REJECTREQUEST]system busy, start flow control for a while"</span>);</span><br><span class="line">            response.setOpaque(opaque);</span><br><span class="line">            ctx.writeAndFlush(response);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">final</span> RequestTask requestTask = <span class="keyword">new</span> RequestTask(run, ctx.channel(), cmd);</span><br><span class="line">            pair.getObject2().submit(requestTask);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RejectedExecutionException e) &#123;</span><br><span class="line">            <span class="keyword">if</span> ((System.currentTimeMillis() % <span class="number">10000</span>) == <span class="number">0</span>) &#123;</span><br><span class="line">                log.warn(RemotingHelper.parseChannelRemoteAddr(ctx.channel())</span><br><span class="line">                    + <span class="string">", too many requests and system thread pool busy, RejectedExecutionException "</span></span><br><span class="line">                    + pair.getObject2().toString()</span><br><span class="line">                    + <span class="string">" request code: "</span> + cmd.getCode());</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (!cmd.isOnewayRPC()) &#123;</span><br><span class="line">                <span class="keyword">final</span> RemotingCommand response = RemotingCommand.createResponseCommand(RemotingSysResponseCode.SYSTEM_BUSY,</span><br><span class="line">                    <span class="string">"[OVERLOAD]system busy, start flow control for a while"</span>);</span><br><span class="line">                response.setOpaque(opaque);</span><br><span class="line">                ctx.writeAndFlush(response);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        String error = <span class="string">" request type "</span> + cmd.getCode() + <span class="string">" not supported"</span>;</span><br><span class="line">        <span class="keyword">final</span> RemotingCommand response =</span><br><span class="line">            RemotingCommand.createResponseCommand(RemotingSysResponseCode.REQUEST_CODE_NOT_SUPPORTED, error);</span><br><span class="line">        response.setOpaque(opaque);</span><br><span class="line">        ctx.writeAndFlush(response);</span><br><span class="line">        log.error(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) + error);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>嗯，很长的一个方法，主要做了下面几件事：</p>
<ol>
<li>从<strong>processorTable</strong>表中获取对应处理器，如果没有，使用默认的<strong>defaultRequestProcessor</strong>处理。这个<strong>defaultRequestProcessor</strong>就是在<strong>NamesrvController</strong>中注册的<strong>Pair&lt;NettyRequestProcessor, ExecutorService&gt;</strong>。</li>
<li>使用<strong>pair</strong>中的<strong>ExecutorService</strong>来提交任务，异步处理<strong>NettyRequestProcessor</strong>中的请求事件处理函数<strong>processRequest()</strong>。</li>
</ol>
<p>看一下<strong>processRequest()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> RemotingCommand <span class="title">processRequest</span><span class="params">(ChannelHandlerContext ctx,</span></span></span><br><span class="line"><span class="function"><span class="params">        RemotingCommand request)</span> <span class="keyword">throws</span> RemotingCommandException </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (ctx != <span class="keyword">null</span>) &#123;</span><br><span class="line">            log.debug(<span class="string">"receive request, &#123;&#125; &#123;&#125; &#123;&#125;"</span>,</span><br><span class="line">                request.getCode(),</span><br><span class="line">                RemotingHelper.parseChannelRemoteAddr(ctx.channel()),</span><br><span class="line">                request);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="keyword">switch</span> (request.getCode()) &#123;</span><br><span class="line">            <span class="keyword">case</span> RequestCode.REGISTER_BROKER:</span><br><span class="line">                Version brokerVersion = MQVersion.value2Version(request.getVersion());</span><br><span class="line">                <span class="keyword">if</span> (brokerVersion.ordinal() &gt;= MQVersion.Version.V3_0_11.ordinal()) &#123;</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">this</span>.registerBrokerWithFilterServer(ctx, request);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">this</span>.registerBroker(ctx, request);</span><br><span class="line">                &#125;</span><br><span class="line">            <span class="keyword">case</span> RequestCode.GET_ROUTEINTO_BY_TOPIC:</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">this</span>.getRouteInfoByTopic(ctx, request);</span><br><span class="line">            <span class="keyword">case</span> RequestCode.GET_BROKER_CLUSTER_INFO:</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">this</span>.getBrokerClusterInfo(ctx, request);</span><br><span class="line">            ......(以下省略一堆<span class="keyword">case</span>)......</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>根据请求码处理一些列的请求事件，有一堆的case，我们甄选出REGISTER_BROKER、GET_ROUTEINTO_BY_TOPIC和GET_TOPICS_BY_CLUSTER三个事件分析一下。</p>
<h3 id="REGISTER-BROKER"><a href="#REGISTER-BROKER" class="headerlink" title="REGISTER_BROKER"></a>REGISTER_BROKER</h3><p>&emsp;&emsp;<strong>REGISTER_BROKER</strong>用于注册并维持broker心跳，上传topic信息。<strong>registerBrokerWithFilterServer</strong>或者<strong>registerBroker</strong>实际都是调用RouteInfoManager的<strong>registerBroker</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> RegisterBrokerResult <span class="title">registerBroker</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String clusterName,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String brokerAddr,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String brokerName,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> <span class="keyword">long</span> brokerId,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String haServerAddr,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> TopicConfigSerializeWrapper topicConfigWrapper,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> List&lt;String&gt; filterServerList,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> Channel channel)</span> </span>&#123;</span><br><span class="line">    RegisterBrokerResult result = <span class="keyword">new</span> RegisterBrokerResult();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.lock.writeLock().lockInterruptibly();</span><br><span class="line"></span><br><span class="line">            Set&lt;String&gt; brokerNames = <span class="keyword">this</span>.clusterAddrTable.get(clusterName);</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> == brokerNames) &#123;</span><br><span class="line">                brokerNames = <span class="keyword">new</span> HashSet&lt;String&gt;();</span><br><span class="line">                <span class="keyword">this</span>.clusterAddrTable.put(clusterName, brokerNames);</span><br><span class="line">            &#125;</span><br><span class="line">            brokerNames.add(brokerName);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">boolean</span> registerFirst = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">            BrokerData brokerData = <span class="keyword">this</span>.brokerAddrTable.get(brokerName);</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> == brokerData) &#123;</span><br><span class="line">                registerFirst = <span class="keyword">true</span>;</span><br><span class="line">                brokerData = <span class="keyword">new</span> BrokerData(clusterName, brokerName, <span class="keyword">new</span> HashMap&lt;Long, String&gt;());</span><br><span class="line">                <span class="keyword">this</span>.brokerAddrTable.put(brokerName, brokerData);</span><br><span class="line">            &#125;</span><br><span class="line">            String oldAddr = brokerData.getBrokerAddrs().put(brokerId, brokerAddr);</span><br><span class="line">            registerFirst = registerFirst || (<span class="keyword">null</span> == oldAddr);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> != topicConfigWrapper</span><br><span class="line">                &amp;&amp; MixAll.MASTER_ID == brokerId) &#123;</span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">this</span>.isBrokerTopicConfigChanged(brokerAddr, topicConfigWrapper.getDataVersion())</span><br><span class="line">                    || registerFirst) &#123;</span><br><span class="line">                    ConcurrentMap&lt;String, TopicConfig&gt; tcTable =</span><br><span class="line">                        topicConfigWrapper.getTopicConfigTable();</span><br><span class="line">                    <span class="keyword">if</span> (tcTable != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        <span class="keyword">for</span> (Map.Entry&lt;String, TopicConfig&gt; entry : tcTable.entrySet()) &#123;</span><br><span class="line">                            <span class="keyword">this</span>.createAndUpdateQueueData(brokerName, entry.getValue());</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            BrokerLiveInfo prevBrokerLiveInfo = <span class="keyword">this</span>.brokerLiveTable.put(brokerAddr,</span><br><span class="line">                <span class="keyword">new</span> BrokerLiveInfo(</span><br><span class="line">                    System.currentTimeMillis(),</span><br><span class="line">                    topicConfigWrapper.getDataVersion(),</span><br><span class="line">                    channel,</span><br><span class="line">                    haServerAddr));</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> == prevBrokerLiveInfo) &#123;</span><br><span class="line">                log.info(<span class="string">"new broker registered, &#123;&#125; HAServer: &#123;&#125;"</span>, brokerAddr, haServerAddr);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (filterServerList != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (filterServerList.isEmpty()) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.filterServerTable.remove(brokerAddr);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="keyword">this</span>.filterServerTable.put(brokerAddr, filterServerList);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (MixAll.MASTER_ID != brokerId) &#123;</span><br><span class="line">                String masterAddr = brokerData.getBrokerAddrs().get(MixAll.MASTER_ID);</span><br><span class="line">                <span class="keyword">if</span> (masterAddr != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    BrokerLiveInfo brokerLiveInfo = <span class="keyword">this</span>.brokerLiveTable.get(masterAddr);</span><br><span class="line">                    <span class="keyword">if</span> (brokerLiveInfo != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        result.setHaServerAddr(brokerLiveInfo.getHaServerAddr());</span><br><span class="line">                        result.setMasterAddr(masterAddr);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.lock.writeLock().unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        log.error(<span class="string">"registerBroker Exception"</span>, e);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个方法使用读写锁来保证线程安全，做了如下几件事：</p>
<ol>
<li>往集群clusterAddrTable表中添加broker，clusterAddrTable是一个集群和broker列表的字典。</li>
<li>往broker列表brokerAddrTable添加broker，brokerAddrTable是一个存放broker信息的字典。</li>
<li>往brokerLiveTable添加broker，brokerLiveTable存放broker的活跃信息，<strong>NamesrvController</strong>中定时扫描不活跃的broker就是根据brokerLiveTable中broker的更新时间来清除broker。</li>
<li>如果broker为master，创建或更新消息队列queueDataList。queueDataList存放topic对应的队列信息，比如队列的broker、读队列数量、写队列数量、topic的读写权限。</li>
<li>更新broker对应的filterServerTable列表</li>
</ol>
<h3 id="GET-ROUTEINTO-BY-TOPIC"><a href="#GET-ROUTEINTO-BY-TOPIC" class="headerlink" title="GET_ROUTEINTO_BY_TOPIC"></a>GET_ROUTEINTO_BY_TOPIC</h3><p>&emsp;&emsp;<strong>GET_ROUTEINTO_BY_TOPIC</strong>根据topic获取路由信息，实质上会调用<strong>RouteInfoManager</strong>的<strong>pickupTopicRouteData</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> TopicRouteData <span class="title">pickupTopicRouteData</span><span class="params">(<span class="keyword">final</span> String topic)</span> </span>&#123;</span><br><span class="line">        TopicRouteData topicRouteData = <span class="keyword">new</span> TopicRouteData();</span><br><span class="line">        <span class="keyword">boolean</span> foundQueueData = <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">boolean</span> foundBrokerData = <span class="keyword">false</span>;</span><br><span class="line">        Set&lt;String&gt; brokerNameSet = <span class="keyword">new</span> HashSet&lt;String&gt;();</span><br><span class="line">        List&lt;BrokerData&gt; brokerDataList = <span class="keyword">new</span> LinkedList&lt;BrokerData&gt;();</span><br><span class="line">        topicRouteData.setBrokerDatas(brokerDataList);</span><br><span class="line"></span><br><span class="line">        HashMap&lt;String, List&lt;String&gt;&gt; filterServerMap = <span class="keyword">new</span> HashMap&lt;String, List&lt;String&gt;&gt;();</span><br><span class="line">        topicRouteData.setFilterServerTable(filterServerMap);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">this</span>.lock.readLock().lockInterruptibly();</span><br><span class="line">                List&lt;QueueData&gt; queueDataList = <span class="keyword">this</span>.topicQueueTable.get(topic);</span><br><span class="line">                <span class="keyword">if</span> (queueDataList != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    topicRouteData.setQueueDatas(queueDataList);</span><br><span class="line">                    foundQueueData = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">                    Iterator&lt;QueueData&gt; it = queueDataList.iterator();</span><br><span class="line">                    <span class="keyword">while</span> (it.hasNext()) &#123;</span><br><span class="line">                        QueueData qd = it.next();</span><br><span class="line">                        brokerNameSet.add(qd.getBrokerName());</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">for</span> (String brokerName : brokerNameSet) &#123;</span><br><span class="line">                        BrokerData brokerData = <span class="keyword">this</span>.brokerAddrTable.get(brokerName);</span><br><span class="line">                        <span class="keyword">if</span> (<span class="keyword">null</span> != brokerData) &#123;</span><br><span class="line">                            BrokerData brokerDataClone = <span class="keyword">new</span> BrokerData(brokerData.getCluster(), brokerData.getBrokerName(), (HashMap&lt;Long, String&gt;) brokerData</span><br><span class="line">                                .getBrokerAddrs().clone());</span><br><span class="line">                            brokerDataList.add(brokerDataClone);</span><br><span class="line">                            foundBrokerData = <span class="keyword">true</span>;</span><br><span class="line">                            <span class="keyword">for</span> (<span class="keyword">final</span> String brokerAddr : brokerDataClone.getBrokerAddrs().values()) &#123;</span><br><span class="line">                                List&lt;String&gt; filterServerList = <span class="keyword">this</span>.filterServerTable.get(brokerAddr);</span><br><span class="line">                                filterServerMap.put(brokerAddr, filterServerList);</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                <span class="keyword">this</span>.lock.readLock().unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            log.error(<span class="string">"pickupTopicRouteData Exception"</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        log.debug(<span class="string">"pickupTopicRouteData &#123;&#125; &#123;&#125;"</span>, topic, topicRouteData);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (foundBrokerData &amp;&amp; foundQueueData) &#123;</span><br><span class="line">            <span class="keyword">return</span> topicRouteData;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>再看一下返回的TopicRouteData结构<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> String orderTopicConf;</span><br><span class="line"><span class="keyword">private</span> List&lt;QueueData&gt; queueDatas;</span><br><span class="line"><span class="keyword">private</span> List&lt;BrokerData&gt; brokerDatas;</span><br><span class="line"><span class="keyword">private</span> HashMap&lt;String<span class="comment">/* brokerAddr */</span>, List&lt;String&gt;<span class="comment">/* Filter Server */</span>&gt; filterServerTable;</span><br></pre></td></tr></table></figure></p>
<p>不就是我们REGISTER_BROKER时注册的信息！</p>
<h3 id="GET-TOPICS-BY-CLUSTER"><a href="#GET-TOPICS-BY-CLUSTER" class="headerlink" title="GET_TOPICS_BY_CLUSTER"></a>GET_TOPICS_BY_CLUSTER</h3><p>&emsp;&emsp;<strong>GET_TOPICS_BY_CLUSTER</strong>根据集群来获取topic列表，实际调用者还是<strong>RouteInfoManager</strong>，贴一下<strong>getTopicsByCluster</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">byte</span>[] getTopicsByCluster(String cluster) &#123;</span><br><span class="line">    TopicList topicList = <span class="keyword">new</span> TopicList();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.lock.readLock().lockInterruptibly();</span><br><span class="line">            Set&lt;String&gt; brokerNameSet = <span class="keyword">this</span>.clusterAddrTable.get(cluster);</span><br><span class="line">            <span class="keyword">for</span> (String brokerName : brokerNameSet) &#123;</span><br><span class="line">                Iterator&lt;Entry&lt;String, List&lt;QueueData&gt;&gt;&gt; topicTableIt =</span><br><span class="line">                    <span class="keyword">this</span>.topicQueueTable.entrySet().iterator();</span><br><span class="line">                <span class="keyword">while</span> (topicTableIt.hasNext()) &#123;</span><br><span class="line">                    Entry&lt;String, List&lt;QueueData&gt;&gt; topicEntry = topicTableIt.next();</span><br><span class="line">                    String topic = topicEntry.getKey();</span><br><span class="line">                    List&lt;QueueData&gt; queueDatas = topicEntry.getValue();</span><br><span class="line">                    <span class="keyword">for</span> (QueueData queueData : queueDatas) &#123;</span><br><span class="line">                        <span class="keyword">if</span> (brokerName.equals(queueData.getBrokerName())) &#123;</span><br><span class="line">                            topicList.getTopicList().add(topic);</span><br><span class="line">                            <span class="keyword">break</span>;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.lock.readLock().unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        log.error(<span class="string">"getAllTopicList Exception"</span>, e);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> topicList.encode();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>根据集群clusterAddrTable获取对应的broker，再遍历并比对topicQueueTable中的broker，如果相等将该topic加入topicList列表。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/RocketMQ之旅/" rel="tag"># RocketMQ之旅</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/18/RocketMQ之旅（一）概述/" rel="next" title="RocketMQ之旅（一）概述">
                <i class="fa fa-chevron-left"></i> RocketMQ之旅（一）概述
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/27/Netty之旅（七）从官方例子展开/" rel="prev" title="Netty之旅（七）从官方例子展开">
                Netty之旅（七）从官方例子展开 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">matrix</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">47</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#NamesrvController"><span class="nav-number">1.</span> <span class="nav-text">NamesrvController</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#NettyRequestProcessor"><span class="nav-number">2.</span> <span class="nav-text">NettyRequestProcessor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#REGISTER-BROKER"><span class="nav-number">3.</span> <span class="nav-text">REGISTER_BROKER</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#GET-ROUTEINTO-BY-TOPIC"><span class="nav-number">4.</span> <span class="nav-text">GET_ROUTEINTO_BY_TOPIC</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#GET-TOPICS-BY-CLUSTER"><span class="nav-number">5.</span> <span class="nav-text">GET_TOPICS_BY_CLUSTER</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">matrix</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>
<div class=BbeiAn-info">
  浙ICP备 -
  <a href="http://www.beian.miit.gov.cn">18040498号</a>
  </a>
</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://luyun.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://yoursite.com/2018/08/18/RocketMQ之旅（二）namesrv/';
          this.page.identifier = '2018/08/18/RocketMQ之旅（二）namesrv/';
          this.page.title = 'RocketMQ之旅（二）namesrv';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://luyun.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
